import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import style from './style.module.scss'

export default () => {
    const [show, setShow] = useState(false)

    return (
        <div>
            <h3>传送门Portal</h3>
            <button onClick={() => setShow(!show)}>弹框控制</button>
            {show && <Dialog />}
        </div>
    )
}

function Dialog() {
    const doc = document
    const node = useRef(doc.createElement('div')).current
    useEffect(() => {
        doc.body.appendChild(node)
        return () => {
            doc.body.removeChild(node)
        }
    }, [])

    // createPortal的作用是把第一个参数react元素挂载到第二个参数node节点上，这里会直接挂载到body下的div中
    return createPortal(
        <div className={style['pop']}>
            <h4>弹窗标题</h4>
            <p>弹窗内容</p>
        </div>,
        node
    )
}
